/**
 * 部门管理管理
 *
 * Created by kongqiang
 * Date 2018/06/13
 */
var scripts = [null,
    ctx + '/resource/plugins/ace/components/jqGrid/js/jquery.jqGrid.js',
    ctx + '/resource/plugins/ace/components/jqGrid/js/i18n/grid.locale-cn.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.zh-CN.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/bootstrapValidator.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/language/zh_CN.js',
    ctx + '/resource/plugins/jquery.jqGrid.patch.src.js',
    ctx + '/resource/plugins/ace/components/_mod/fuelux/tree.js',
    ctx + '/resource/plugins/ace/assets/js/src/elements.treeview.js',
    ctx + '/resource/utils/deptTreeData.js',
    null];
pageContentArea.ace_ajax('loadScripts', scripts, function () {
    jQuery(function ($) {
        // 初始化树
        $('#deptTreeview').ace_tree({
            dataSource: remoteDeptDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': true,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        }).on('selected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        }).on('deselected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        });

        // 初始化列表
        var grid_selector = '#grid-table';
        var $grid_selector = $(grid_selector);
        var pager_selector = '#grid-pager';
        var parent_column = $grid_selector.closest('[class*="col-"]');
        var colNames = [
             '部门ID',
             '部门编码',
             '部门名称',
             '部门描述',
             '上级部门编码',
             '上级部门名称',
             '部门级别',
             '是否叶子节点',
             '是否删除',
             '创建人',
             '创建时间',
             '修改人',
             '修改时间',
             '公司ID',
             '经理ID',
             '上级部门ID',
             '区域',
             '是否小组',
             '管理单位ID',
             '部门ID备份',
             '是否有效'
        ];
        var width = pageContentArea.width() / colNames.length;
        var colModels = [
            {name: 'deptId', index: 'deptId', hidden: true},
            {name: 'deptCode', index: 'deptCode', hideWidth: 300, width: width},
            {name: 'deptName', index: 'deptName', hideWidth: 300, width: width},
            {name: 'deptDesc', index: 'deptDesc', hideWidth: 650, width: width},
            {name: 'parentCode', index: 'parentCode', hidden: true},
            {name: 'parentName', index: 'parentName', hideWidth: 650, width: width},
            {name: 'treeLevel', index: 'treeLevel', hidden: true},
            {name: 'isLeaf', index: 'isLeaf', hidden: true},
            {name: 'isDelete', index: 'isDelete', hidden: true},
            {name: 'creater', index: 'creater', hidden: true},
            {name: 'createDate', index: 'createDate', hidden: true},
            {name: 'modifier', index: 'modifier', hidden: true},
            {name: 'modifieDate', index: 'modifieDate', hidden: true},
            {name: 'compId', index: 'compId', hidden: true},
            {name: 'mgrId', index: 'mgrId', hidden: true},
            {name: 'superDeptId', index: 'superDeptId', hidden: true},
            {name: 'area', index: 'area', hidden: true},
            {name: 'isTeam', index: 'isTeam', hidden: true},
            {name: 'manageUnitId', index: 'manageUnitId', hidden: true},
            {name: 'deptIdBak', index: 'deptIdBak', hidden: true},
            {name: 'status', index: 'status', hidden: true}
        ];
        $grid_selector.jqGrid({
            url: ctx + '/tbSysDept/queryPageList',
            mtype: 'post',
            datatype: 'local',
            height: '100%',
            colNames: colNames,
            colModel: colModels,
            autowidth: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: rowNum,
            rowList: rowList,
            pager: pager_selector,
            sortname: 'deptId',
            sortorder: 'asc',
            jsonReader: jsonReader,
            beforeRequest: function () {
                var postData = {};
                $('#queryPanel').find('[name^="search."]').each(function () {
                    var $this = $(this);
                    postData[$this.attr('name').replace(/search\./, '')] = $this.val();
                });
                // 获取部门管理树节点
                var selectedItems = $('#deptTreeview').tree('selectedItems');
                if (isNotEmpty(selectedItems)) {
                    postData['parentCode'] = selectedItems[0].additionalParameters.id;
                } else {
                    postData['parentCode'] = null;
                }
                $.extend($grid_selector.getGridParam('postData'), postData);
            },
            loadComplete: function () {
                setTimeout(function () {
                    $grid_selector.jqGrid('setGridWidth', parent_column.width());
                }, 20);
            },
            ondblClickRow: viewGridRow
        });

        //navButtons
        $grid_selector.jqGrid('navGrid', pager_selector, {
            add: false, edit: false, del: false, search: false, view: false, refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green'
        }).navSeparatorAdd(pager_selector, {
            sepclass: 'ui-separator',
            sepcontent: ''
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '查看详细信息',
            buttonicon: 'ace-icon fa fa-search-plus info',
            onClickButton: viewGridRow,
            position: 'first'
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '导出Excel',
            buttonicon: 'ace-icon fa fa-file-excel-o green',
            onClickButton: expRowsToExcel,
            position: 'last'
        });

        // 默认展开树，选中第一个节点
        $('#deptTreeview').tree('openFolder', $('#deptTreeview').find('.tree-branch')[1]);
        $('#deptTreeview').tree('selectFolder', $('#deptTreeview').find('.tree-branch')[1]);

        // Form表单
        var theForm = $('#editTbSysDeptForm');

        $('#addBtn').click(function () {
            var selectedItems = $('#deptTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)){
                // 重置表单验证
                resetValidator();
                // 隐藏隐藏项
                $('.show').removeClass('show').addClass('hidden');
                // 显示保存按钮
                $('#saveTbSysDeptBtn').removeClass('hidden');
                // 重置表单基本元素
                theForm.formReset();
                // 填充表单
                $(':input[name="parentName"]').val(selectedItems[0].text);
                $(':input[name="parentCode"]').val(selectedItems[0].additionalParameters.id);
                $(':input[name="isLeaf"]').val('1');
                $(':input[name="treeLevel"]').val(selectedItems[0].additionalParameters.treeLevel + 1);
                // 启用deptCode验证
                $(':input[name="deptCode"]').removeAttr('readonly','readonly');
                theForm.bootstrapValidator('enableFieldValidators', 'deptCode', false);
                // 显示弹出层
                $.launchDialog('tbSysDeptModal');
            } else {
                $(this).dynamicPop('请在部门管理树选择部门!');
            }
        });

        $('#editBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录编辑, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var deptId = $grid_selector.jqGrid('getRowData', rowId).deptId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbSysDept/querySingle',
                    dataType: 'json',
                    data: {
                        deptId: deptId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 隐藏隐藏项
                        $('.show').removeClass('show').addClass('hidden');
                        // 禁用deptCode验证
                        $(':input[name="deptCode"]').attr('readonly','readonly');
                        theForm.bootstrapValidator('enableFieldValidators', 'deptCode', false);
                        // 显示保存按钮
                        $('#saveTbSysDeptBtn').removeClass('hidden');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbSysDeptModal');
                    }
                });
            }
        });

        $('#delBtn').click(function () {
            // 判断删除项是否包含子节点
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            var flag = false;
            for (var i = 0; i < rowIds.length; i++) {
                var isLeaf = $grid_selector.jqGrid('getRowData', rowIds[i]).isLeaf;
                if (isLeaf == 0) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                $(this).dynamicPop('请先删除子节点!');
            } else {
                // 获取选中的列表项
                var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
                if (rowIds.length > 0) {
                    $(this).confirm('确认要删除吗？', function () {
                        var ids = new Array();
                        $.each(rowIds, function (idx, rowId) {
                            var row = $grid_selector.jqGrid('getRowData', rowId);
                            ids.push(row.deptId);
                        });
                        $.ajax({
                            async: true,// 异步请求
                            type: 'post',
                            url: ctx + '/tbSysDept/delete',
                            dataType: 'json',
                            data: {
                                ids: ids.join(',')
                            },
                            success: function (data) {
                                if (data) {
                                    // 删除成功将表格刷新
                                    $grid_selector.trigger('reloadGrid', [{page: 1}]);
                                    // 更新部门树
                                    var selectedItems = $('#deptTreeview').tree('selectedItems');
                                    if (isNotEmpty(selectedItems)) {
                                        if (data.result.length == 1) {
                                            $('#deptTreeview').tree('refreshFolder', $('.tree-selected').parent().parent());
                                        } else {
                                            $('#deptTreeview').tree('refreshFolder', $('.tree-selected'));
                                        }
                                    } else {
                                        $('#deptTreeview').tree('collapse');
                                    }
                                }
                            }
                        });
                    });
                } else {
                    $(this).dynamicPop('请从列表中选择一条记录删除!');
                }
            }
        });

        // 保存
        $('#saveTbSysDeptBtn').click(function () {
            //开启验证
            theForm.data('bootstrapValidator').validate();
            if (theForm.data('bootstrapValidator').isValid()) {
                $.ajax({
                    async: true,// 异步请求
                    type: 'post',
                    dataType: 'json',
                    url: ctx + '/tbSysDept/save',
                    data: JSON.stringify(theForm.serializeObject()),
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success == true) {
                            $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            // 关闭窗口
                            $('#tbSysDeptModal').modal('hide');
                            // 更新部门树
                            var selectedItems = $('#deptTreeview').tree('selectedItems');
                            if (isNotEmpty(selectedItems)) {
                                $('#deptTreeview').tree('refreshFolder', $('.tree-selected'));
                            } else {
                                $('#deptTreeview').tree('collapse');
                            }
                            $.successMessage(data.msg, pageContentArea);
                        } else {
                            $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                        }
                    },
                    error: function () {
                        $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                    }
                });
            }
        });

        function viewGridRow() {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要查看的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录查看, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var deptId = $grid_selector.jqGrid('getRowData', rowId).deptId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbSysDept/querySingle',
                    dataType: 'json',
                    data: {
                        deptId: deptId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 显示隐藏项
                        theForm.find('.hidden').removeClass('hidden').addClass('show');
                        // 隐藏保存按钮
                        $('#saveTbSysDeptBtn').addClass('hidden');
                        $(':input[name="deptCode"]').removeAttr('readonly');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbSysDeptModal');
                    }
                });
            }
        }

        // 导出excel
        function expRowsToExcel() {
            var colFieldViewNames = new Array();
            var colFieldNames = new Array();
            $.each(colModels, function (idx, obj) {
                if(obj.hidden == false || obj.hidden == undefined){
                    colFieldNames.push(obj.index);
                    colFieldViewNames.push(colNames[idx]);
                }
            });
            var sortName = $grid_selector.jqGrid('getGridParam', 'sortname');// 排序列
            var sortOrder = $grid_selector.jqGrid('getGridParam', 'sortorder');// 排序方式：desc、asc
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            postData.titles = colFieldViewNames;
            postData.fields = colFieldNames;
            postData.sidx = sortName;
            postData.sord = sortOrder;
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbSysDept/expExcel',
                dataType: 'json',
                data: postData,
                success: function (data) {
                    downloadFile(data.result);// 下载文件
                }
            });
        }

        // 表单验证
        function formValidator() {
            theForm.bootstrapValidator({
                group: '.rowGroup',
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    deptCode: {
                        message: '部门编码验证失败',
                        validators: {
                            threshold: 1, //有1字符以上才发送ajax请求
                            remote: {//ajax验证,result:{"valid",true or false}, 表示正确: {"valid",true}
                                url: ctx + '/tbSysDept/checkInputField',
                                message: '部门编码已存在',
                                delay: 1000,//设置1秒发送一次ajax（默认输入一个字符，提交一次）
                                type: 'POST',//请求方式
                                //自定义提交数据, 默认值提交当前input value
                                data: function (validator) {
                                    return {
                                        inputName: 'deptCode',
                                        inputValue: $('[name="deptCode"]').val()
                                    };
                                }
                            },
                            notEmpty: {
                                message: '部门编码不能为空'
                            },
                            stringLength: {
                                max: 50,
                                message: '部门编码长度不能大于50'
                            }
                        }
                    },
                    deptName: {
                        message: '部门名称验证失败',
                        validators: {
                            notEmpty: {
                                message: '部门名称不能为空'
                            },
                            stringLength: {
                                max: 40,
                                message: '部门名称长度不能大于40'
                            }
                        }
                    },
                    deptDesc: {
                        message: '部门描述验证失败',
                        validators: {
                            stringLength: {
                                max: 255,
                                message: '部门描述长度不能大于255'
                            }
                        }
                    }
                }
            });
        }

        // 初始化表单验证
        formValidator();

        //重置表单验证
        function resetValidator() {
            var bootstrapValidator = theForm.data('bootstrapValidator');
            if (bootstrapValidator) {
                bootstrapValidator.destroy();
                theForm.data('bootstrapValidator', null);
                formValidator();
            }
        }

        // 显示隐藏查询条件
        $('#searBtn').click(function () {
            $(this).find('i').toggleClass('fa-arrow-down');
            $(this).find('i').toggleClass('fa-arrow-up');
        });

        $('#searchBtn').click(function () {
            $grid_selector.trigger('reloadGrid', [{page: 1}]);
        });

        // 重置查询表单
        $('#resetBtn').click(function () {
            $('#queryPanel').find(':input(:text)').each(function () {
                $(this).val('');
            });
            $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
                $(this).removeAttr('checked');
            });
            reloadJqGrid('json');
        });

        // 刷新JqGrid列表
        function reloadJqGrid(datatype) {
            $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
        }

        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });

        $('.input-daterange').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            //todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        });

        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $grid_selector.jqGrid('setGridWidth', parent_column.width());
        });

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });

    });

});
